import { effectScope, inject, isReactive, isRef, reactive } from "vue";
import { isFunction, formatArgs, isComputed } from "./utils";
import { piniaSymbol } from "./global";
export const defineStore = (...args) => {
  const { id, options, setup } = formatArgs(args);
  const isSetup = isFunction(setup);
  function useStore() {
    const pinia = inject(piniaSymbol);
    if (!pinia.store.has(id)) {
      if (isSetup) {
        createSetupStore(pinia, id, setup);
      } else {
        createOptionsStore();
      }
    }
    return pinia.store.get(id);
  }
  return useStore;
};
function createSetupStore(pinia, id, setup) {
  const setupStore = setup();
  const store = reactive({});
  let setupScope;
  const result = pinia.scope.run(() => {
    setupScope = effectScope();
    return setupScope.run(() => compileSetup(pinia, id, setupStore));
  });
  pinia.store.set(id, store);
  Object.assign(store, result);
  return store;
}
function createOptionsStore() {}
function compileSetup(pinia, id, setupStore) {
  !pinia.state.value && (pinia.state.value = {});
  !pinia.state.value[id] && (pinia.state.value[id] = {});
  for (let key in setupStore) {
    const el = setupStore[key];
    if ((isRef(el) && !isComputed(el)) || isReactive(el)) {
      pinia.state.value[id][key] = el;
    }
  }
  return {
    ...setupStore,
  };
}
